package com.ad.aidai.activitys.main;

import android.content.Context;

import com.ad.aidai.bean.Version;
import com.ad.aidai.common.ADApp;
import com.ad.aidai.common.RongImManager;
import com.ad.aidai.network.NetWork;
import com.ad.aidai.network.StatusCodeFromNet;
import com.ad.aidai.network.result.NetResultWithData;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by Yusxon on 17/2/28.
 */

public class MainPresenter implements MainContract.Presenter {


    private Context mContext;
    private MainContract.View mView;
    private CompositeSubscription mSubscriptions;

    public MainPresenter(Context context, MainContract.View view) {
        this.mContext = context;
        this.mView = view;
        mView.setPresenter(this);
    }

    @Override
    public void subscribe() {
        mSubscriptions = new CompositeSubscription();
    }

    @Override
    public void unSubscribe() {
        mContext = null;
        mView = null;
        mSubscriptions.clear();
    }

    @Override
    public void loadData() {
        RongImManager.connect();
        ADApp.loadSchoolPlace();
        checkUpdate();
    }

    private void checkUpdate() {
        NetWork.getAppApi()
                .getVersion()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NetResultWithData<Version>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        MobclickAgent.reportError(mContext, e);
                        Logger.t("AboutPresenter").e(e.getMessage());
                    }

                    @Override
                    public void onNext(NetResultWithData<Version> versionNetResult) {
                        Logger.t("AboutPresenter").i(versionNetResult.toString());
                        if (versionNetResult.getCode() == StatusCodeFromNet.CODE_SUCCESS) {
                            Version version = versionNetResult.getData();
                            if (!version.getVersionId().equals(ADApp.getVersionName())) {
                                mView.showUpdateDialog(version.getVersionId(), version.getVersionMessage());
                            }
                        }
                    }
                });
    }

    @Override
    public void updateApp() {

    }
}
